/**
 * 区块链网络配置
 * 定义支持的区块链网络及其配置信息
 */

export const NETWORKS = {
  ethereum: {
    name: "以太坊",
    chainId: "0x1", // 主网
    testChainId: "0xaa36a7", // Sepolia测试网
    rpcUrl: "https://sepolia.infura.io/v3/your_key",
    symbol: "ETH",
    blockExplorer: "https://sepolia.etherscan.io",
    isTestnet: true,
    icon: "ethereum.svg",
  },
  bsc: {
    name: "币安智能链",
    chainId: "0x38", // 主网
    testChainId: "0x61", // 测试网
    rpcUrl: "https://data-seed-prebsc-1-s1.binance.org:8545",
    symbol: "BNB",
    blockExplorer: "https://testnet.bscscan.com",
    isTestnet: true,
    icon: "binance.svg",
  },
  polygon: {
    name: "Polygon",
    chainId: "0x89", // 主网
    testChainId: "0x13881", // Mumbai测试网
    rpcUrl: "https://rpc-mumbai.maticvigil.com",
    symbol: "MATIC",
    blockExplorer: "https://mumbai.polygonscan.com",
    isTestnet: true,
    icon: "polygon.svg",
  },
  arbitrum: {
    name: "Arbitrum",
    chainId: "0xa4b1", // 主网
    testChainId: "0x66eed", // Sepolia测试网
    rpcUrl: "https://sepolia-rollup.arbitrum.io/rpc",
    symbol: "ETH",
    blockExplorer: "https://sepolia.arbiscan.io",
    isTestnet: true,
    icon: "arbitrum.svg",
  },
};

/**
 * 获取所有支持的网络列表
 * @returns {Array} 网络列表
 */
export function getNetworkList() {
  return Object.keys(NETWORKS).map((key) => ({
    id: key,
    ...NETWORKS[key],
  }));
}

/**
 * 获取指定网络的配置
 * @param {string} networkId 网络ID
 * @returns {Object} 网络配置
 */
export function getNetwork(networkId) {
  return NETWORKS[networkId] || NETWORKS.ethereum; // 默认返回以太坊网络
}

/**
 * 切换MetaMask网络
 * @param {string} networkId 网络ID
 * @returns {Promise<boolean>} 是否成功切换
 */
export async function switchNetwork(networkId) {
  if (!window.ethereum) {
    throw new Error("MetaMask未安装");
  }

  const network = getNetwork(networkId);
  const chainId = network.isTestnet ? network.testChainId : network.chainId;

  try {
    // 尝试切换到指定网络
    await window.ethereum.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId }],
    });
    return true;
  } catch (error) {
    // 如果网络不存在，则添加网络
    if (error.code === 4902) {
      try {
        await window.ethereum.request({
          method: "wallet_addEthereumChain",
          params: [
            {
              chainId,
              chainName: network.name,
              nativeCurrency: {
                name: network.symbol,
                symbol: network.symbol,
                decimals: 18,
              },
              rpcUrls: [network.rpcUrl],
              blockExplorerUrls: [network.blockExplorer],
            },
          ],
        });
        return true;
      } catch (addError) {
        console.error("添加网络失败:", addError);
        throw new Error("添加网络失败");
      }
    }
    console.error("切换网络失败:", error);
    throw error;
  }
}
